package ign.behaviours.generator;

import ign.ProgramParams;
import ign.agents.Building;
import jade.core.Agent;
import jade.core.behaviours.TickerBehaviour;
import jade.wrapper.AgentContainer;
import jade.wrapper.AgentController;
import jade.wrapper.StaleProxyException;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Comportement générant des Buildings au hasard sur la carte.
 * @author Simon Bourigaut & Ghislain Di Paolo
 */
public class Generation extends TickerBehaviour {
	private static final long serialVersionUID = -4213680250593147884L;
	
	Random rand;
	float proba = 0.8f;
	int nb_building;
	
	/**
	 * Constructeur basique pour un {@link TickerBehaviour}.
	 * @param a	l'agent créateur
	 * @param period le gap entre deux executions.
	 */
	public Generation(Agent a, long period) {
		super(a, period);
		
		rand = new Random();
		nb_building = 0;
	}
	
	/**
	 * Renvoie le nombre de buildings créés.
	 * @return 
	 */
	public int getNbBuildings(){
		
		return nb_building;
	}

	@Override
	protected void onTick() {
		
		if (nb_building > 40){
			return;
//			if (rand.nextFloat() > proba)
//				return;
//			
//			proba *= 0.90;
		}
		
		/* New building */
		int new_x = 0, new_y = 0;
		if (ProgramParams.restrictive_area){
			new_x = rand.nextInt(200) + 250;
			new_y = rand.nextInt(200) + 250;
		}
		else {
			new_x = rand.nextInt(ProgramParams.window_width - 200) + 100;
			new_y = rand.nextInt(ProgramParams.window_height - 200) + 100;
		}
		
		int new_width = (rand.nextInt(50) + 20);
		int new_height = (rand.nextInt(50) + 20);
		
		Building build = new Building(new_x, new_y, new_width, new_height);
		
		AgentContainer ac = myAgent.getContainerController();
		try {
			
			AgentController bac = ac.acceptNewAgent("building_" + String.format("%06d", nb_building), build);
			bac.start();
			
		} catch (StaleProxyException e) {
			Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, e);
			return;
		}
		
		nb_building++;
	}

}
